package com.egdigital.allzic.ui.activity;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.android.volley.VolleyError;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserUpdate;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Updater;
import com.egdigital.allzic.utils.NetworkManager;
import com.egdigital.allzic.utils.PrefManager;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;

import fr.nomeo.AppsPanel;
import fr.nomeo.conf.APConfiguration;

@APConfiguration(appkey = "iuJZatgO", appName = "allzicradio", projectID = "946456735176", myActivity = ActivityLauncher.class, notificationIcon = R.drawable.icon)
public class ActivityLauncher extends SherlockActivity {
	
	private static final String	TAG							= ActivityLauncher.class.getSimpleName();	// log
	private static final int	SPLASH_SCREEN_DELAY			= 2000;
	private static final int	SPLASH_SCREEN_SECOND_DELAY	= 1000;
	private static final int	SPLASH_LOGO_DELAY			= 1000;
	private Handler				mFirstRunHandler;
	private Runnable			mFirstRunRunnable;
	private ImageView			mLogo;
	private TextView			mVersion;
	private YoYo.YoYoString		mAnimationControl;														// to cancel animation
	//
	private boolean				mDialogUp					= false;
	private JsonParserUpdate	mJsonParserUpdate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		AppsPanel.getInstance().onCreate(this);
		
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);// allow music volume
		// layout
		setContentView(R.layout.activity_launcher);
		// views
		mLogo = (ImageView) findViewById(R.id.launcher_logo);
		mVersion = (TextView) findViewById(R.id.launcher_version);
		try {
			mVersion.setText("version " + (getPackageManager().getPackageInfo(getPackageName(), 0).versionName));
		} catch (NameNotFoundException e) {
		}
		// first animation fadein on the logo
		mAnimationControl = YoYo.with(Techniques.FadeIn).duration(SPLASH_LOGO_DELAY).withListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator arg0) {
			}

			@Override
			public void onAnimationRepeat(Animator arg0) {
			}

			@Override
			public void onAnimationEnd(Animator arg0) {
				// get last version info from web service
				if (NetworkManager.isConnectedFast(getApplicationContext())) {
					VolleyManager.init(ActivityLauncher.this);
					mJsonParserUpdate = JsonParserUpdate.getInstance();
					setupUpdateDataListener();
					loadData();
				} else {
					mDialogUp = false;
					// second animation zoomout on the logo
					mAnimationControl = YoYo.with(Techniques.ZoomOut).delay(500).duration(500).playOn(mLogo);
				}
			}

			@Override
			public void onAnimationCancel(Animator arg0) {
			}
		}).playOn(mLogo);
		// handler and runnable
		mFirstRunHandler = new Handler();
		mFirstRunRunnable = new Runnable() {

			@Override
			public void run() {
				if (!mDialogUp) {
					moveToNextActivity();
				}
			}
		};
		mFirstRunHandler.postDelayed(mFirstRunRunnable, SPLASH_SCREEN_DELAY);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	protected void onRestart() {
		AppsPanel.getInstance().onRestart();
		super.onRestart();
	}

	@Override
	protected void onStop() {
		AppsPanel.getInstance().onStop();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (mJsonParserUpdate != null) {
			mJsonParserUpdate.stopRequestQueue();
		}
		super.onDestroy();
	}

	public void moveToTuto(boolean doAnimation) {
		Intent intent = new Intent(this, ActivityTuto.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		finish();
		startActivity(intent);
		if (doAnimation) {
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
	}

	public void moveToHome(boolean doAnimation) {
		Intent intent = new Intent(this, ActivityHome.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		finish();
		startActivity(intent);
		if (doAnimation) {
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
	}

	private void moveToNextActivity() {
		PrefManager prefs = PrefManager.getInstance(getApplicationContext());
		if (prefs.getBoolean_prefForKey("firstrun")) {
			prefs.addBoolean_Pref("firstrun", false);
			moveToTuto(true);
		} else {
			moveToHome(true);
		}
	}

	private void stopAnimation() {
		mAnimationControl.stop(true);
		if (mFirstRunHandler != null) {
			mFirstRunHandler.removeCallbacks(mFirstRunRunnable);
		}
	}

	private void showDialog(String title, String text) {
		new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle(title).setMessage(text).setPositiveButton("Oui", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {
				/* User clicked OK so do some stuff */
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + "com.egdigital.allzic"));
				startActivity(intent);
			}
		}).setNegativeButton("Non", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {
				moveToNextActivity();
			}
		}).show();
	}

	/**
	 * download updates json
	 */
	private void setupUpdateDataListener() {
		mJsonParserUpdate.setJsonCallBack(new JsonCallBack() {

			@Override
			public void downloadStarted() {
				// do nothing
			}

			@Override
			public void downloadPercent(int percent) {
				// do nothing
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				moveToNextActivity();
			}

			@Override
			public <T> void downloadCompleted(List<T> list) {
				if (!list.isEmpty()) {
					try {
						Updater updater = ((List<Updater>) list).get(0);
						// test the last version
						if (Integer.parseInt(updater.getmId()) > (getPackageManager().getPackageInfo(getPackageName(), 0).versionCode)) {
							mDialogUp = true;
							// open the update dialog
							showDialog(updater.getmTitle(), updater.getmText());
						} else {
							mDialogUp = false;
						}
					} catch (Exception e) {
					}
				}
				// in case
				if (!mDialogUp) {
					mFirstRunHandler.removeCallbacks(mFirstRunRunnable);
					mFirstRunHandler.postDelayed(mFirstRunRunnable, SPLASH_SCREEN_SECOND_DELAY);
					mAnimationControl = YoYo.with(Techniques.ZoomOut).delay(500).duration(500).playOn(mLogo);
				}
			}
		});
	}

	private void loadData() {
		if (NetworkManager.isConnected(getApplicationContext())) {
			mJsonParserUpdate.extractJsonObjectData(getString(R.string.url_rating));
		}
	}
}
